package com.ruoyi.project.common.service.impl;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.ruoyi.framework.config.QiNiuConfig;
import com.ruoyi.project.common.service.ICommonService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * 通用Service
 */
@Service
public class CommonServiceImpl implements ICommonService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private QiNiuConfig qiNiuConfig;
    /**
     * 图片前缀
     */
    private String FILE_SUFFIX = "zm_img_";

    /**
     * 七牛云上传图片
     *
     * @param file
     * @return
     * @throws IOException
     */
    @Override
    public String uploadQiNiu(MultipartFile file) {
        return uploadQiNiu(file, "");
    }
    @Override
    public String uploadQiNiu(String file) {
        return uploadQiNiu(file, "");
    }

    @Override
    public String uploadQiNiu(String file, String fileName) {
        String suffix = file.substring(file.lastIndexOf('.'));
        String key = StringUtils.isEmpty(fileName) ? FILE_SUFFIX + System.currentTimeMillis() + suffix : fileName;
        return uploadQiNiu(file, key);
    }
    /**
     * 七牛云上传图片 自定义文件名
     *
     * @param file
     * @return
     * @throws IOException
     */
    @Override
    public String uploadQiNiu(MultipartFile file, String fileName) {
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
        String key = StringUtils.isEmpty(fileName) ? FILE_SUFFIX + System.currentTimeMillis() + suffix : fileName;
        return save(file, key);
    }
    /**
     * 保存到七牛云
     * @param file
     * @param key
     * @return
     */
    public String save(MultipartFile file, String key) {
        try {
            // 获取机房信息// 构造一个带指定Region对象的配置类
            Configuration cfg = new Configuration(qiNiuConfig.getRegion());
            UploadManager uploadManager = new UploadManager(cfg);

            // 对账户进行认证
            Auth auth = Auth.create(qiNiuConfig.getAccessKey(), qiNiuConfig.getSecretKey());
            String upToken = auth.uploadToken(qiNiuConfig.getBucket());

            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(file.getBytes());
            Response response = uploadManager.put(byteInputStream, key, upToken, null, null);
            // 解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return putRet.key;
        } catch (QiniuException e) {
            Response r = e.response;
            // 不抱错其实就已经是上传成功
            logger.error("QiNiu Upload Error :", r.toString());
            try {
                logger.error("QiNiu Upload  Error body :", r.bodyString());
            } catch (QiniuException ex2) {
                //ignore 忽略即可
            }
        } catch (Exception e) {
            logger.error("QiNiu Error :", e.toString());
        }
        return "";
    }

    /**
     * 保存到七牛云
     * @param file
     * @param key
     * @return
     */
    public String save(String file, String key) {
        try {
            // 获取机房信息// 构造一个带指定Region对象的配置类
            Configuration cfg = new Configuration(qiNiuConfig.getRegion());
            UploadManager uploadManager = new UploadManager(cfg);
            // 对账户进行认证
            Auth auth = Auth.create(qiNiuConfig.getAccessKey(), qiNiuConfig.getSecretKey());
            String upToken = auth.uploadToken(qiNiuConfig.getBucket());
            Response response = uploadManager.put(file, key, upToken);
            // 解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return putRet.key;
        } catch (QiniuException e) {
            Response r = e.response;
            // 不抱错其实就已经是上传成功
            logger.error("QiNiu Upload Error :", r.toString());
            try {
                logger.error("QiNiu Upload  Error body :", r.bodyString());
            } catch (QiniuException ex2) {
                //ignore 忽略即可
            }
        } catch (Exception e) {
            logger.error("QiNiu Error :", e.toString());
        }
        return "";
    }
}
